import json
import logging
from celery import shared_task
from django.utils import timezone
from django.db import transaction
from utils.myRedis import myRedis
from utils.baidu_ai import BaiduAIConfig
from .models import User, RealNameVerification

logger = logging.getLogger(__name__)

@shared_task
def process_verification_queue():
    """
    处理实名认证队列的定时任务
    每秒执行一次，每次最多处理3条任务
    """
    try:
        # 获取队列中的任务，每次最多处理3条
        for i in range(3):
            # 从队列中获取任务
            task_data = myRedis.lpop('verification_queue')
            if not task_data:
                logger.info("队列为空，无任务需要处理")
                break
            
            try:
                # 解析任务数据
                task = json.loads(task_data)
                user_id = task.get('user_id')
                image_url = task.get('image_url')
                
                if not user_id or not image_url:
                    logger.error(f"任务数据格式错误: {task_data}")
                    continue
                
                # 处理单个认证任务
                process_single_verification(user_id, image_url)
                
            except json.JSONDecodeError as e:
                logger.error(f"任务数据JSON解析失败: {task_data}, 错误: {e}")
            except Exception as e:
                logger.error(f"处理任务失败: {task_data}, 错误: {e}")
                
    except Exception as e:
        logger.error(f"处理认证队列时发生错误: {e}")

def process_single_verification(user_id, image_url):
    """
    处理单个实名认证任务
    """
    try:
        # 获取用户和认证记录
        user = User.objects.get(id=user_id)
        verification = RealNameVerification.objects.get(
            user=user, 
            image_url=image_url,
            status='pending'
        )
        
        # 更新状态为处理中
        verification.status = 'processing'
        verification.save()
        
        # 调用百度AI识别身份证
        baidu_ai = BaiduAIConfig()
        result = baidu_ai.recognize_id_card(image_url)
        
        if result['success']:
            # 识别成功，更新数据库
            with transaction.atomic():
                verification.name = result['name']
                verification.id_number = result['code']
                verification.status = 'verified'
                verification.save()
                
                # 更新用户认证状态
                user.is_verified = True
                user.save()
                
                # 将识别结果存入Redis
                result_key = f"verification_result:{image_url}"
                result_data = {
                    'name': result['name'],
                    'code': result['code']
                }
                myRedis.set(result_key, json.dumps(result_data), ex=3600)  # 1小时过期
                
                logger.info(f"用户 {user_id} 实名认证成功，姓名: {result['name']}")
                
        else:
            # 识别失败
            verification.status = 'failed'
            verification.save()
            logger.error(f"用户 {user_id} 身份证识别失败: {result.get('error', '未知错误')}")
            
    except User.DoesNotExist:
        logger.error(f"用户不存在: {user_id}")
    except RealNameVerification.DoesNotExist:
        logger.error(f"认证记录不存在: user_id={user_id}, image_url={image_url}")
    except Exception as e:
        logger.error(f"处理认证任务时发生错误: user_id={user_id}, 错误: {e}")
        # 更新状态为失败
        try:
            verification = RealNameVerification.objects.get(
                user_id=user_id, 
                image_url=image_url
            )
            verification.status = 'failed'
            verification.save()
        except:
            pass 